package cn.easy.service.impl;

import cn.easy.api.FtpService;
import cn.easy.common.pojo.MyFile;
import cn.easy.common.util.FtpUtil;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;


import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.UUID;

/**
 * ftp 文件上传
 *
 * @author 谢子豪
 * @time 2017/11/6
 * @description
 */
@Service
public class FtpServiceImpl implements FtpService {
    @Value("${FTP_ADDRESS}")
    private String ftpAddress;//ftp地址
    @Value("${FTP_PORT}")
    private int ftpPort;//ftp端口号
    @Value("${FTP_USERNAME}")
    private String ftpUserName;//ftp账号
    @Value("${FTP_PASSWORD}")
    private String ftpPassword;//ftp密码
    @Value("${FTP_BASE_PATH}")
    private String ftpBasePath;//照片在ftp服务器上保存的位置
    @Value("${IMAGE_BATH_URL}")
    private String imageBathUrl;//图片服务器目录

    @Override
    public String uploadFile(String serStr) throws Exception {
        MultipartFile file = null;
        String TEMP_ENCODING = "ISO-8859-1";
        String DEFAULT_ENCODING = "UTF-8";
        ByteArrayInputStream byteArrayInputStream = null;
        ObjectInputStream objectInputStream = null;
        try {
            String deserStr = java.net.URLDecoder.decode(serStr, DEFAULT_ENCODING);
            byteArrayInputStream = new ByteArrayInputStream(deserStr.getBytes(TEMP_ENCODING));
            objectInputStream = new ObjectInputStream(byteArrayInputStream);
            file = (MultipartFile) objectInputStream.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            objectInputStream.close();
            byteArrayInputStream.close();
        }

        //获取文件后缀
        if(file==null) return "空的";
        String filename = file.getOriginalFilename();
        String[] split = filename.split("\\.");
        String fileDir = "ddd";
        if (split.length == 0) {
            throw new Exception("文件格式错误");
        }
        String prex = split[split.length - 1];
        //创建新的文件名
        String saveFile = UUID.randomUUID() + "." + prex;

        FtpUtil.uploadFile(ftpAddress, ftpPort, ftpUserName, ftpPassword, ftpBasePath, fileDir, saveFile, file.getInputStream());
        return ftpBasePath+"#"+fileDir+"#"+saveFile;
    }
}
